package com.ai.imagetext.controller;

import com.ai.imagetext.dto.IdListRequest;
import com.ai.imagetext.dto.ImageDTO;
import com.ai.imagetext.service.ImageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/images")
@RequiredArgsConstructor
@Tag(name = "图片管理", description = "图片相关的API接口")
public class ImageController {

    private final ImageService imageService;

    /**
     * 获取所有图片（分页）
     */
    @Operation(summary = "获取所有图片", description = "分页获取所有图片列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllImages(
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段", example = "createdAt") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortDir) {

        log.info("Getting all images: page={}, size={}, sortBy={}, sortDir={}", page, size, sortBy, sortDir);

        try {
            Page<ImageDTO> imagePage = imageService.getAllImages(page, size, sortBy, sortDir);

            Map<String, Object> response = createSuccessResponse("获取图片列表成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get all images failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 根据ID获取图片
     */
    @Operation(summary = "根据ID获取图片", description = "根据图片ID获取图片详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "404", description = "图片不存在"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getImageById(
            @Parameter(description = "图片ID", example = "1") @PathVariable Long id) {
        log.info("Getting image by ID: {}", id);

        try {
            Optional<ImageDTO> image = imageService.getImageById(id);

            if (image.isPresent()) {
                // 增加使用次数
                imageService.incrementUsageCount(id);

                Map<String, Object> response = createSuccessResponse("获取图片详情成功");
                response.put("data", image.get());
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.notFound().build();
            }

        } catch (Exception e) {
            log.error("Get image by ID failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 搜索图片
     */
    @Operation(summary = "搜索图片", description = "根据关键词搜索图片")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchImages(
            @Parameter(description = "搜索关键词", example = "风景") @RequestParam String keyword,
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段", example = "createdAt") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortDir) {

        log.info("Searching images with keyword: {}", keyword);

        try {
            Page<ImageDTO> imagePage = imageService.searchImages(keyword, page, size, sortBy, sortDir);

            Map<String, Object> response = createSuccessResponse("搜索图片成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));
            response.put("keyword", keyword);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Search images failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 根据标签筛选图片
     */
    @GetMapping("/tag/{tagName}")
    public ResponseEntity<Map<String, Object>> getImagesByTag(@PathVariable String tagName) {
        log.info("Getting images by tag: {}", tagName);

        try {
            List<ImageDTO> images = imageService.getImagesByTag(tagName);

            Map<String, Object> response = createSuccessResponse("根据标签筛选图片成功");
            response.put("data", images);
            response.put("tag", tagName);
            response.put("count", images.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images by tag failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 根据多个标签筛选图片
     */
    @GetMapping("/tags")
    public ResponseEntity<Map<String, Object>> getImagesByTags(@RequestParam List<String> tags) {
        log.info("Getting images by tags: {}", tags);

        try {
            List<ImageDTO> images = imageService.getImagesByTags(tags);

            Map<String, Object> response = createSuccessResponse("根据多标签筛选图片成功");
            response.put("data", images);
            response.put("tags", tags);
            response.put("count", images.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images by tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 根据文件类型筛选图片
     */
    @GetMapping("/type/{mimeType}")
    public ResponseEntity<Map<String, Object>> getImagesByMimeType(@PathVariable String mimeType) {
        log.info("Getting images by MIME type: {}", mimeType);

        try {
            // 处理路径参数中的斜杠
            String actualMimeType = mimeType.replace("-", "/");
            List<ImageDTO> images = imageService.getImagesByMimeType(actualMimeType);

            Map<String, Object> response = createSuccessResponse("根据文件类型筛选图片成功");
            response.put("data", images);
            response.put("mimeType", actualMimeType);
            response.put("count", images.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images by MIME type failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 根据时间范围筛选图片
     */
    @GetMapping("/date-range")
    public ResponseEntity<Map<String, Object>> getImagesByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {

        log.info("Getting images by date range: {} to {}", startTime, endTime);

        try {
            List<ImageDTO> images = imageService.getImagesByDateRange(startTime, endTime);

            Map<String, Object> response = createSuccessResponse("根据时间范围筛选图片成功");
            response.put("data", images);
            response.put("startTime", startTime);
            response.put("endTime", endTime);
            response.put("count", images.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images by date range failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取热门图片
     */
    @GetMapping("/popular")
    public ResponseEntity<Map<String, Object>> getPopularImages(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        log.info("Getting popular images: page={}, size={}", page, size);

        try {
            Page<ImageDTO> imagePage = imageService.getPopularImages(page, size);

            Map<String, Object> response = createSuccessResponse("获取热门图片成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get popular images failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 按使用次数排序获取图片
     */
    @Operation(summary = "按使用次数排序获取图片", description = "根据图片使用次数进行排序")
    @GetMapping("/sorted/usage")
    public ResponseEntity<Map<String, Object>> getImagesSortedByUsage(
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortDir) {

        log.info("Getting images sorted by usage: page={}, size={}, sortDir={}", page, size, sortDir);

        try {
            Page<ImageDTO> imagePage = imageService.getImagesSortedByUsage(page, size, sortDir);

            Map<String, Object> response = createSuccessResponse("按使用次数排序获取图片成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images sorted by usage failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 按时间排序获取图片
     */
    @Operation(summary = "按时间排序获取图片", description = "根据图片更新时间或创建时间进行排序")
    @GetMapping("/sorted/time")
    public ResponseEntity<Map<String, Object>> getImagesSortedByTime(
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "时间字段", example = "updatedAt") @RequestParam(defaultValue = "updatedAt") String timeField,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortDir) {

        log.info("Getting images sorted by time: page={}, size={}, timeField={}, sortDir={}", page, size, timeField, sortDir);

        try {
            Page<ImageDTO> imagePage = imageService.getImagesSortedByTime(page, size, timeField, sortDir);

            Map<String, Object> response = createSuccessResponse("按时间排序获取图片成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images sorted by time failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取用户的图片
     * @author wangguiyou
     */
    @Operation(summary = "获取用户的图片", description = "根据用户ID分页获取用户上传的图片列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    @GetMapping("/user")
    public ResponseEntity<Map<String, Object>> getImagesById(
            @Parameter(description = "用户ID", example = "1") @RequestParam() long userId,
            @Parameter(description = "页码，从0开始", example = "0") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段", example = "createdAt") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortDir) {

        log.info("Getting images by user ID: {}, page={}, size={}, sortBy={}, sortDir={}", userId, page, size, sortBy, sortDir);

        try {
            Page<ImageDTO> imagePage = imageService.getImagesByUserId(userId, page, size, sortBy, sortDir);

            Map<String, Object> response = createSuccessResponse("获取用户图片列表成功");
            response.put("data", imagePage.getContent());
            response.put("pagination", createPaginationInfo(imagePage));
            response.put("userId", userId);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get images by user ID failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 更新图片信息
     */
    @PostMapping("/{id}/update")
    public ResponseEntity<Map<String, Object>> updateImage(@PathVariable Long id, @RequestBody ImageDTO imageDTO) {
        log.info("Updating image: {}", id);

        try {
            ImageDTO updatedImage = imageService.updateImage(id, imageDTO);

            Map<String, Object> response = createSuccessResponse("更新图片信息成功");
            response.put("data", updatedImage);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Update image failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }


    /**
     * 删除图片
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteImages(@PathVariable Long id) {
        log.info("Deleting image: {}", id);

        try {
            imageService.deleteImage(id);

            Map<String, Object> response = createSuccessResponse("删除图片成功");
            response.put("imageId", id);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Delete image failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 删除图片
     */
    @PostMapping("/{id}/delete")
    public ResponseEntity<Map<String, Object>> deleteImage(@PathVariable Long id) {
        log.info("Deleting image: {}", id);

        try {
            imageService.deleteImage(id);

            Map<String, Object> response = createSuccessResponse("删除图片成功");
            response.put("imageId", id);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Delete image failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 批量删除图片
     */
    @PostMapping("/batch-delete")
    public ResponseEntity<Map<String, Object>> deleteImages(@RequestBody IdListRequest Ir) {

        try {
            List<Long> ids = Ir.getIds();
            log.info("Batch deleting images: {}", ids);
            imageService.deleteImages(ids);

            Map<String, Object> response = createSuccessResponse("批量删除图片成功");
            response.put("deletedIds", ids);
            response.put("count", ids.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Batch delete images failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取图片统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getImageStatistics() {
        log.info("Getting image statistics");

        try {
            ImageService.ImageStatistics stats = imageService.getImageStatistics();

            Map<String, Object> response = createSuccessResponse("获取图片统计信息成功");
            response.put("data", stats);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get image statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取热门标签
     */
    @GetMapping("/popular-tags")
    public ResponseEntity<Map<String, Object>> getPopularTags(@RequestParam(defaultValue = "10") int limit) {
        log.info("Getting popular tags with limit: {}", limit);

        try {
            List<ImageService.TagStatistics> tags = imageService.getPopularTags(limit);

            Map<String, Object> response = createSuccessResponse("获取热门标签成功");
            response.put("data", tags);
            response.put("limit", limit);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get popular tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 创建分页信息
     */
    private Map<String, Object> createPaginationInfo(Page<?> page) {
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("currentPage", page.getNumber());
        pagination.put("totalPages", page.getTotalPages());
        pagination.put("totalElements", page.getTotalElements());
        pagination.put("size", page.getSize());
        pagination.put("hasNext", page.hasNext());
        pagination.put("hasPrevious", page.hasPrevious());
        return pagination;
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}
